import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { MediaItem, PlaybackHistory } from '../types/media'

export const useMediaStore = defineStore('media', () => {
  // 状态
  const currentMedia = ref<MediaItem | null>(null)
  const mediaList = ref<MediaItem[]>([])
  const playbackHistory = ref<PlaybackHistory[]>([])
  const isPlaying = ref(false)
  const currentTime = ref(0)
  const duration = ref(0)
  const volume = ref(1)
  const playbackRate = ref(1)
  const audioEffect = ref('normal')
  const quality = ref('auto')

  // 计算属性
  const hasMedia = computed(() => currentMedia.value !== null)
  const progress = computed(() => {
    if (duration.value === 0) return 0
    return (currentTime.value / duration.value) * 100
  })

  // 方法
  const setCurrentMedia = (media: MediaItem) => {
    currentMedia.value = media
    if (!mediaList.value.find(m => m.id === media.id)) {
      mediaList.value.push(media)
    }
  }

  const addToPlaylist = (media: MediaItem) => {
    if (!mediaList.value.find(m => m.id === media.id)) {
      mediaList.value.push(media)
    }
  }

  const removeFromPlaylist = (id: string) => {
    mediaList.value = mediaList.value.filter(m => m.id !== id)
  }

  const updatePlaybackHistory = (mediaId: string, time: number) => {
    const existing = playbackHistory.value.find(h => h.mediaId === mediaId)
    if (existing) {
      existing.lastPosition = time
      existing.lastPlayed = new Date()
    } else {
      playbackHistory.value.push({
        mediaId,
        lastPosition: time,
        lastPlayed: new Date(),
      })
    }
  }

  const clearHistory = () => {
    playbackHistory.value = []
  }

  const setAudioEffect = (effect: string) => {
    audioEffect.value = effect
  }

  const setQuality = (qualityLevel: string) => {
    quality.value = qualityLevel
  }

  const init = () => {
    // 从本地存储恢复数据
    const savedHistory = localStorage.getItem('playbackHistory')
    if (savedHistory) {
      playbackHistory.value = JSON.parse(savedHistory)
    }
    
    const savedVolume = localStorage.getItem('volume')
    if (savedVolume) {
      volume.value = parseFloat(savedVolume)
    }
  }

  const saveToLocalStorage = () => {
    localStorage.setItem('playbackHistory', JSON.stringify(playbackHistory.value))
    localStorage.setItem('volume', volume.value.toString())
  }

  return {
    // 状态
    currentMedia,
    mediaList,
    playbackHistory,
    isPlaying,
    currentTime,
    duration,
    volume,
    playbackRate,
    audioEffect,
    quality,
    
    // 计算属性
    hasMedia,
    progress,
    
    // 方法
    setCurrentMedia,
    addToPlaylist,
    removeFromPlaylist,
    updatePlaybackHistory,
    clearHistory,
    setAudioEffect,
    setQuality,
    init,
    saveToLocalStorage,
  }
})
